<template>
  <div class="admin-dashboard">
    <el-card class="admin-container" shadow="hover">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="用户管理" name="users">
          <div class="search-container">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名/邮箱"
              class="search-input"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="showAddDialog">新增用户</el-button>
          </div>
          <el-table :data="filteredUsers" style="margin-top:20px;">
            <el-table-column prop="user_id" label="ID" width="60" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="user_type" label="角色" />
            <el-table-column prop="is_active" label="激活" :formatter="formatActive" />
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="editUser(row)">编辑状态</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog :title="dialogTitle" v-model="dialogVisible">
            <el-form :model="formData" label-width="100px">
              <el-form-item label="用户名">
                <el-input v-model="formData.username" disabled />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.email" disabled />
              </el-form-item>
              <el-form-item label="角色">
                <el-input v-model="formData.user_type" disabled />
              </el-form-item>
              <el-form-item v-if="!isEditing" label="密码">
                <el-input type="password" v-model="formData.password" />
              </el-form-item>
              <el-form-item label="激活">
                <el-switch v-model="formData.is_active" active-value="true" inactive-value="false" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveUser">保存</el-button>
            </template>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="招聘信息管理" name="jobs">
          <JobsManagement />
        </el-tab-pane>
        <el-tab-pane label="求职信息管理" name="resumes">
          <ResumesManagement />
        </el-tab-pane>
        <el-tab-pane label="帖子管理" name="posts">
          <PostsManagement />
        </el-tab-pane>
        <el-tab-pane label="资源管理" name="resources">
          <ResourcesManagement />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import JobsManagement from '../components/JobsManagement.vue'
import ResumesManagement from '../components/ResumesManagement.vue'
import PostsManagement from '../components/PostsManagement.vue'
import ResourcesManagement from '../components/ResourcesManagement.vue'

const auth = useAuthStore()
const activeTab = ref('users')
const users = ref([])
const searchQuery = ref('')
const dialogVisible = ref(false)
const isEditing = ref(false)
const dialogTitle = ref('')

const formData = reactive({
  user_id: null,
  username: '',
  email: '',
  user_type: '',
  phone:'',
  password: '',
  is_active: true
})

const filteredUsers = computed(() => {
  if (!searchQuery.value) return users.value
  const query = searchQuery.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(query) ||
    user.email.toLowerCase().includes(query)
  )
})

const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

const fetchUsers = async () => {
  try {
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/users?operator_id=${auth.userId}`, {
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    users.value = await res.json()
  } catch (err) {
    ElMessage.error('获取用户列表失败: ' + err.message)
  }
}

const showAddDialog = () => {
  isEditing.value = false
  dialogTitle.value = '新增用户'
  Object.assign(formData, { user_id: null, username: '', email: '', user_type: 'job_seeker', password: '', is_active: true })
  dialogVisible.value = true
}

const editUser = (user) => {
  isEditing.value = true
  dialogTitle.value = '编辑用户'
  Object.assign(formData, { user_id: user.user_id, username: user.username, email: user.email, user_type: user.user_type, password: '', is_active: user.is_active })
  dialogVisible.value = true
}

const saveUser = async () => {
  try {
    if (!formData.username || !formData.email || !formData.user_type) {
      ElMessage.warning('请填写完整信息')
      return
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      return ElMessage.warning('请输入有效的邮箱地址')
    }
    const token = auth.token
    let res
    if (isEditing.value) {
      res = await fetch(`http://127.0.0.1:8000/api/users/${formData.user_id}?operator_id=${auth.userId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
        body: JSON.stringify({ is_active: formData.is_active })
      })
    } else {
      res = await fetch(`http://127.0.0.1:8000/api/users`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${encodeURIComponent(token)}` },
        body: JSON.stringify({ username: formData.username, email: formData.email, password: formData.password, user_type: formData.user_type, phone: null, is_active: formData.is_active})
      })
    }
    const data = await res.json()
    if (!res.ok) throw new Error(data.detail || '操作失败')
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchUsers()
  } catch (err) {
    ElMessage.error(err.message)
  }
}

const deleteUser = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该用户吗？', '提示', { type: 'warning' })
    const token = auth.token
    const res = await fetch(`http://127.0.0.1:8000/api/users/${id}?operator_id=${auth.userId}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${encodeURIComponent(token)}` }
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error(err.message || '删除失败')
  }
}

const formatActive = (row) => row.is_active ? '是' : '否'

onMounted(fetchUsers)
</script>

<style scoped>
.admin-dashboard {
  padding: 0;
  background-color: #f0f2f5;
}
.admin-container {
  margin: 20px;
  padding: 20px;
  border-radius: 8px;
  background-color: #ffffff;
}
.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}
.search-input {
  width: 300px;
}
.admin-container .el-button {
  margin-bottom: 12px;
}
.admin-container .el-table {
  background-color: #ffffff;
}
</style> 